/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.inspur.edp.lcm.metadata.shell;

import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.stream.Collectors;
import org.jline.reader.Parser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.shell.Shell;
import org.springframework.shell.jline.InteractiveShellApplicationRunner;

/**
 * @Description: 自定义命令Runner, 启动应用后直接执行多条命令, 执行后结束
 */
@Order(InteractiveShellApplicationRunner.PRECEDENCE - 50)  // order 越小, 越先执行
public class StringCommandRunner implements ApplicationRunner {

    @Lazy
    @Autowired
    private Parser parser;

    @Lazy
    @Autowired
    private Shell shell;

    @Lazy
    @Autowired
    private ConfigurableEnvironment environment;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //过滤掉所有@开头的参数, @开头的参数交给ScriptShellApplicationRunner 处理
        List<String> cmds = args.getNonOptionArgs().stream()
            .filter(s -> !s.startsWith("@"))
            .collect(Collectors.toList());

        //如果启动参数中, 命令不为空, 则执行
        if (cmds.size() > 0) {
            // 关闭交互式应用: 确保关闭应用后, 直接退出应用, 不停留在交互式窗口中
            InteractiveShellApplicationRunner.disable(environment);

            // 将所有命令存储到队列中
            Queue<String> queue = new PriorityQueue<>(cmds);

            // 执行命令
            shell.run(new StringInputProvider(parser, queue));
        }
    }
}